#!/usr/bin/env python

import os, sys, getopt

import utility


# given job file, analyze user behavior
# return a dict
def analyze_user_behavior(file_name, period_time):
    with open(file_name, "r") as f:
        task_records = f.readlines()

    result = {}
    task_in_period = {}
    for record in task_records:
        (task_id, start_time, end_time) = [int(i) for i in record.split()]
        start_period = start_time / period_time
        end_period = (end_time-1) / period_time
        for period in range(start_period, end_period+1):
            if task_id not in task_in_period:
                task_in_period[task_id] = {}
            task_in_period[task_id][period] = True

    for (task_id, period) in task_in_period.items():
        for p in period:
            if p not in result:
                result[p] = 0
            result[p] += 1
    return result


# main framework trigger the process
def process_user_folders(begin_index, end_index, period_time):
    output_prefix = "output/"
    user_behavior_suffix = "user_behavior_of_"+str(period_time)+"/"
    user_behavior_folder = output_prefix+user_behavior_suffix
    if not os.path.exists(user_behavior_folder):
        os.system("mkdir "+user_behavior_folder)

    for i in range(begin_index, end_index):
        user_index = str(i)
        if i < 10:
            user_index = "00"+user_index
        elif i < 100:
            user_index = "0"+user_index

        if not os.path.exists(user_behavior_folder+user_index):
            os.system("mkdir "+user_behavior_folder+user_index)

        original_folder = output_prefix+user_index+"/"
        if not os.path.exists(original_folder):
            continue
        
        for single_class in os.listdir(original_folder):
            user_behavior = {}
            task_collection = os.listdir(original_folder+single_class)
            for job_id in task_collection:
                task_file = original_folder+single_class+"/"+job_id
                task_behavior_by_priority = analyze_user_behavior(task_file, period_time)
                
                for (period, times) in task_behavior_by_priority.items():
                    if period not in user_behavior:
                        user_behavior[period] = 0
                    user_behavior[period] += times

            target_file = user_behavior_folder+user_index+"/"+single_class
            with open(target_file, "w") as f:
                time_periods = user_behavior.keys()
                time_periods.sort()
                for period in time_periods:
                    line = str(period)+" "+str(user_behavior[period])+"\n"
                    f.write(line)

        # priority_collection = os.listdir(original_folder)
        # for j in range(13):
        #     if str(j) in priority_collection:
        #         priority_collection.remove(str(j))

        # for priority in priority_collection:
        #     user_behavior = {}
        #     task_collection = os.listdir(original_folder+priority)
        #     for job_id in task_collection:
        #         task_file = original_folder+priority+"/"+job_id
        #         task_behavior_by_priority = analyze_user_behavior(task_file, period_time)
                
        #         for (period, times) in task_behavior_by_priority.items():
        #             if period not in user_behavior:
        #                 user_behavior[period] = 0
        #             user_behavior[period] += times

        #     target_file = user_behavior_folder+user_index+"/"+priority
        #     with open(target_file, "w") as f:
        #         time_periods = user_behavior.keys()
        #         time_periods.sort()
        #         for period in time_periods:
        #             line = str(period)+" "+str(user_behavior[period])+"\n"
        #             f.write(line)


def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hp:b:e:")
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)

    # set default value
    begin_index = 0
    end_index = 932
    period_time = 300

    for o, s in opts:
        # help information
        if o == "-h":
            print "usage -p <period time>"
            print "      -b <begin user index>"
            print "      -e <end user index>"
            return
        elif o == "-b":
            begin_index = int(s)
        elif o == "-e":
            end_index = int(s)
        elif o == "-p":
            period_time = int(s)

    process_user_folders(begin_index, end_index, period_time)
    

if __name__ == "__main__":
    main(sys.argv)